from lexical_analysis import LexicalAnalysis

a = []
index = 0
e = 0


def E():
    print("E->TE'\n")
    T()
    E1()


def E1():
    if a[index] == '+' or a[index] == '-':
        print("E1->ATE'\n")
        A()
        T()
        E1()
    else:
        print("E'->ε\n")


def T():
    print("T->FT'\n")
    F()
    T1()


def T1():
    if a[index] == '*' or a[index] == '/':
        print("T1->MFT'\n")
        M()
        F()
        T1()
    else:
        print("T'->ε\n")


def F():
    global index
    global e
    if (a[index] == '('):
        index += 1
        E()
        if (a[index] == ')'):
            print("F->(E)")
        else:
            print("error!")
            e = 1
    elif a[index] == "i":
        index += 1
        print("F->i")
    else:
        print("error happend!")
        e = 1


def A():
    global index
    global e
    if a[index] == '+':
        print("A->+\n")
        index = index + 1
    else:
        if a[index] == '-':
            print("A->-\n")
            index = index + 1
        else:
            print("error3!\n")
            e = 1


def M():
    global index
    global e
    if a[index] == '*':
        print("M->*\n")
        index = index + 1
    else:
        if a[index] == '/':
            print("M->/ \n")
            index = index + 1
        else:
            print("error!\n")
            e = 1


if __name__ == '__main__':
    lex = LexicalAnalysis("../test_data/testPreDeal1.txt", "../test_data/example/00_arr_defn2.sy")
    lex.read()
    lex.process()
    tok = lex.token
    print(tok)
    data = ''.join(open("../test_data/testPreDeal1.txt", 'r').readlines())
    listWord = []
    for aTok in tok:
        for a in aTok:
            if 'ID' in aTok[a]:
                listWord.append(a)
    listWord = sorted(listWord, key=lambda i: len(i), reverse=True)
    print("ID list：")
    print(listWord)
    for word in listWord:
        data = data.replace(word, "i")
    a = data
    E()
    
    if e != 1:
        print("Right")
    else:
        print("Wrong")
